package com.fany.fastsearcher.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;

public abstract class ListViewActivity extends BaseActivity implements AbsListView.OnScrollListener,
		AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener
{
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(getContentViewID());
		getListView().setOnItemClickListener(this);
		getListView().setOnItemLongClickListener(this);
		getListView().setOnScrollListener(this);
	}

	// AbsListView.OnScrollListener
	@Override
	public void onScrollStateChanged(AbsListView absListView, int scrollState)
	{
		if (_lastItem >= absListView.getAdapter().getCount() && scrollState == SCROLL_STATE_IDLE)
		{
			onScrollToEnd();
            return;
		}
		if (absListView.getFirstVisiblePosition() == 0)
		{
			onScrollToHead();
            return;
		}
	}

	@Override
	public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount)
	{
		_lastItem = firstVisibleItem + visibleItemCount;
	}

	protected void onScrollToEnd()
	{
	}

	protected void onScrollToHead()
	{
	}

	// AdapterView.OnItemClickListener
	@Override
	public void onItemClick(AdapterView<?> adapterView, View view, int index, long l)
	{
		onItemClick(index);
	}

	protected void onItemClick(int index)
	{
	}

	// View.OnLongClickListener
	@Override
	public boolean onItemLongClick(AdapterView<?> adapterView, View view, int index, long l)
	{
		onItemLongClick(index);
		return true;
	}

	protected void onItemLongClick(int index)
	{
	}

	protected abstract int getListViewID();

	protected abstract int getContentViewID();

	protected void setAdapter(ListAdapter adapter)
	{
		getListView().setAdapter(adapter);
	}

	protected ListView getListView()
	{
		if (_listView == null)
		{
			_listView = (ListView) findViewById(getListViewID());
		}
		return _listView;
	}

	public void setPosition(int position)
	{
		getListView().setSelection(position);
	}

	private int _lastItem;
	private ListView _listView;
}
